<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\brand\BrandActivity;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;

    public function indexPost(Request $request, Content $content)
    {
        $name = $request->input('name', '');
        $value = $request->input('value', '');
        $id = $request->input('pk', 0);
        if ($name && $id > 0) {
            FineGoodsModel::update([$name => $value], ['id' => $id]);
            return response()->json([
                'status' => true,
                'message' => "success",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }


    }

    public function index(Request $request, Content $content)
    {
        Admin::style('.span-label{margin-bottom: 5px; cursor: pointer; margin-right: 5px; display: inline-block;}');
        Admin::script($this->operateScript());
        if (is_null($request->input('activity_state'))) {
            $request->merge([
                'activity_state' => FineGoodsModel::STATE_WAIT
            ]);
        }
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $wikiData = [];
        if (!is_null($condition)) {
            $where = $condition;
            $where['LIMIT'] = [
                ($page - 1) * $page_size,
                $page_size
            ];
            $where['ORDER'] = ['addtime' => 'DESC'];
            $result['list'] = FineGoodsModel::selectList($where);
            $basicIds = array_column($result['list'], 'basic_id');
            $basicIds = $basicIds ? array_filter(array_unique($basicIds)) : [];
            $wikiData = $basicIds ? mWiki::getDefaultWikiInfoByBasicIds($basicIds, ['id', 'basic_id', 'title']) : [];
            $wikiData = $wikiData ? array_column($wikiData, null, 'basic_id') : [];
            unset($where['LIMIT']);
            unset($where['ORDER']);
            $result['total'] = FineGoodsModel::selectCount($where);
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        if (isset($result['list']) && !empty($result['list'])) {
            $fineGoodsIds = array_column($result['list'], 'id');
            $joinMap = FineGoodsService::getApplyCount($fineGoodsIds);
            foreach ($result['list'] as &$item) {
                $item['join_num'] = $joinMap[$item['id']] ?? 0;
            }
        }
        $categoryTagMap = FineGoodsModel::CATEGORY_TAG_MAP;
        $categoryTagMap[0] = '未选中标签';
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $wikiData, $categoryTagMap) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->dropDown('brand_value', [
                            'brand_id' => '品牌ID',
                            'brand_name' => '品牌名称',
                        ]);
                        $filter->dropDown('activity_value', [
                            'id' => '活动ID',
                            'goods_name' => '活动标题',
                        ]);
                    });
                    $filter->column(1 / 3, function (Grid\Filter $filter) {
                        $typeMap = FineGoodsModel::TYPE_MAP;
                        unset($typeMap[FineGoodsModel::TYPE_EVALUATION_OLD]);
                        $filter->equal('type', '活动类型')->select($typeMap);
                    });
                    $filter->column(1 / 3, function (Grid\Filter $filter) {
                        $filter->equal('activity_state', '活动状态')->select(FineGoodsModel::ACTIVITY_STATE);
                        $filter->date('schedule_start_time', '上线时间');
                    });
                    $filter->expand();
                });
                $grid->column("id", '活动ID')->width(60);
                $grid->column('activity_title', '活动标题')->display(function () {
                    $url = BrandActivity::getFindGoodsTestLink($this->id);
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li><a href="' . url('/admin/goodsTest/detail/' . $this->id) . '">' . $this->activity_title . '</a></li>';
                    $html .= '<li>' . $this->package_combination_name . '</li>';
                    $html .= '<li style="color: #00a65a ">';
                    $html .= '<a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $url . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                    $html .= '活动地址</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('type', '活动类型')->display(function () {
                    return FineGoodsModel::TYPE_MAP[$this->type];
                })->width(100);
                $grid->column('beautify_num', '美化人数')->editable()->help('请输入正整数');
                $grid->column('join_num', '申请人数');

                $grid->column('category_tag_id', '标签')->editable('select', $categoryTagMap);
                $grid->column('brand_id', '品牌')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>ID:' . $this->brand_id . '</li>';
                    $html .= '<li>' . $this->brand_name . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('prize_type', '商品信息')->display(function () use ($wikiData) {
                    $html = '<ul class="list-unstyled">';
                    $wikiId = $wikiData[$this->basic_id]['id'] ?? 0;
                    $h5Url = Hhzurl::getDomain() . '/shop/goods-detail/wiki?basic_id=' . $this->basic_id . '&no-pc-redirect=true';
                    if ($wikiId) {
                        $h5Url = Hhzurl::getDomain() . '/shop/goods-detail/wiki?wiki_id=' . $wikiId . '&no-pc-redirect=true';
                    }
                    $html .= '<li>WIKI ID：<a class="fa" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                shade: 0.8,
                                shadeClose: true,
                                area: [\'500px\', \'600px\'],
                                content: \'' . $h5Url . '\'
                            });">' . $this->basic_id . '</a></li>';
                    $html .= '<li>' . $this->basic_title . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('cover_img_url', '活动头图')->image("", 100, 100);
                $grid->column('dynamic_img', '中奖动态')->display(function () {
                    $img = BrandActivity::getActivityDynamicImg(BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $this->dynamic_img);
                    $str = '<span style="color: red;font-weight: bolder;font-size: medium">添加动态图</span>';
                    $html = '<ul class="list-unstyled">';
                    if ($this->dynamic_img) {
                        $html .= '<img src="' . $img . '" style="max-width:100px;max-height:100px" class="img img-thumbnail">';
                        $str = '更改动态图';
                    }
                    $html .= '<li><a href="/admin/goodsTest/index/' . $this->id . '/editDynamic">' . $str . '</a></li>';
                    $html .= '</ul>';
                    return $html;
                });
                $grid->column('goods_num', '商品数量')->width(80);
                $grid->column('goods_worth', '商品单价')->width(100);
                $grid->column('activity_state', '活动状态')->display(function () {
                    return FineGoodsModel::ACTIVITY_STATE[$this->activity_state];
                })->width(100);
                $grid->column('', '报名列表')->display(function () {
                    if (in_array($this->activity_state, [FineGoodsModel::STATE_APPLYING, FineGoodsModel::STATE_VERIFY, FineGoodsModel::STATE_EXPERIENCING, FineGoodsModel::STATE_OUTPUT_REPORT])) {
                        //if (in_array($this->activity_state, [FineGoodsModel::STATE_VERIFY, FineGoodsModel::STATE_EXPERIENCING, FineGoodsModel::STATE_OUTPUT_REPORT])) {
                        return '<span><a href="' . url('/admin/goodsTest/join/' . $this->id . '/list') . '" class="btn btn-default viewPeople" data-type=""   data-id="' . $this->id . '" >查看</a></span>';
                    }
                })->width(80);
                $grid->column('start_time', '排期')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    if ($this->schedule_start_time == 0) {
                        $html .= '<li>待排期</li>';
                    } else {
                        $html .= '<li>' . date('Y-m-d', $this->schedule_start_time) . '</li>';
                        $html .= '<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;至</li>';
                        $html .= '<li>' . date('Y-m-d', $this->schedule_end_time) . '</li>';
                    }
                    //if ($this->activity_state == FineGoodsModel::STATE_TO_BE_ONLINE) {
                    $html .= '<li><a href="javascript:;" class="btn btn-default editTime" data-type=""   data-id="' . $this->id . '" >更改排期</a></li>';
                    //} todo 临时放开
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if ($actions->row->activity_state == FineGoodsModel::STATE_WAIT) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa pass-data" data-state="' . FineGoodsModel::STATE_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">通过</a>');
                        $actions->prepend('&nbsp;&nbsp;<a class="fa not-pass-data" data-state="' . FineGoodsModel::STATE_NOT_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">不通过</a>');
                    } else if (in_array($actions->row->activity_state, [FineGoodsModel::STATE_EXPERIENCING, FineGoodsModel::STATE_OUTPUT_REPORT])) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa" href="' . url('/admin/goodsTest/reportList/index/' . $actions->row->id) . '">选择评测内容</a>');
                    } else if ($actions->row->activity_state != FineGoodsModel::STATE_DEL && $actions->row->activity_state != FineGoodsModel::STATE_WAIT) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa del-data" data-state="' . FineGoodsModel::STATE_DEL . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消活动</a>');
                    }

                    if ($actions->row->activity_state == FineGoodsModel::STATE_OUTPUT_REPORT) {
                        $btnTitle = $actions->row->activity_data ? '编辑数据' : '上传数据';
                        $actions->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="fa fa-bar-chart" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑数据\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'600px\'],
                                content: \'/admin/goodsTest/index/' . $actions->row->id . '/activityData\'
                            });" title="' . $btnTitle . '"><i class="fa"></i><span class="hidden-xs">' . $btnTitle . '</span></a>
</div>');
                    }

                });
            }
        );
        $tab = new Tab();
        $tab->add('审核列表', $gridList->render(), true);
        $tab->addLink('创建测评活动', url("/admin/goodsTest/index/createTestActivity"), false);
        $content->row($tab);
        return $content
            ->header('审核列表')
            ->description(' ')
            ->breadcrumb(['text' => '审核列表']);
    }

    public function editTime(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info = FineGoodsModel::first(['id' => $id]);
        $info['schedule_start_time'] = $info['schedule_start_time'] ? date('Y-m-d', $info['schedule_start_time']) : '';
        $info['schedule_end_time'] = $info['schedule_end_time'] ? date('Y-m-d', $info['schedule_end_time']) : '';
        $form = new Form($info);
        $form->hidden('request_url', '');
        $form->text('id', '活动ID')->readonly();
        $form->select('activity_state', '活动状态')->options(FineGoodsModel::ACTIVITY_STATE)->readOnly()->disable();
        $form->date('schedule_start_time', '开始时间');
        $form->date('schedule_end_time', '结束时间');
        $form->action('/admin/goodsTest/index/changeTime');
        $desc = '';
        if (!in_array($info['activity_state'], [FineGoodsModel::STATE_TO_BE_ONLINE])) {
//            $form->disableSubmit();
//            $form->disableReset();
//            $desc = '当前状态不支持排期'; todo 临时放开
        }
        $content->row($form);
        return $content
            ->header('活动「' . $info['activity_title'] . '」排期')
            ->description($desc);
    }

    public function changeTime(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $startTime = $request->input('schedule_start_time', '');
            $endTime = $request->input('schedule_end_time', '');
            $startTime = $startTime ? strtotime(date('Y-m-d', strtotime($startTime))) : 0;
            $endTime = $endTime ? strtotime(date('Y-m-d', strtotime($endTime))) + 86399 : 0;
            $info = $id ? FineGoodsModel::first(['id' => $id]) : [];
            if ($startTime >= $endTime) {
                throw new \Exception('开始时间必须小于结束时间');
            }
            if (empty($id) || empty($info)) {
                throw new \Exception('不存在的活动');
            }
            //if ($info['activity_state'] != FineGoodsModel::STATE_TO_BE_ONLINE) {
            //throw new \Exception('当前状态不支持排期');
            //} todo 临时放开
            $adminId = Admin::user()->id;
            $data = [
                'schedule_start_time' => $startTime,
                'schedule_end_time' => $endTime,
                'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                'operate_uid' => $adminId
            ];
            $result = FineGoodsModel::updateData($data, ['id' => $id]);
            $stateArr = [
                FineGoodsModel::STATE_PASS,
                FineGoodsModel::STATE_TO_BE_ONLINE,
                FineGoodsModel::STATE_APPLYING,
                FineGoodsModel::STATE_VERIFY,
                FineGoodsModel::STATE_EXPERIENCING,
                FineGoodsModel::STATE_OUTPUT_REPORT,
            ];
            if (in_array($info['activity_state'], $stateArr)) {
                BrandActivityBasic::updateActivityBasic($id, BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $info['brand_id'], $info['basic_id'], $startTime, $endTime);
            }
            if ($info['type'] < FineGoodsModel::TYPE_EVALUATION) { //只有轻测和开箱类型活动 需要通知品牌后台
                $activityName = FineGoodsModel::TYPE_MAP_BACKUPS[$info['type']];
                $msg = "你所提报的 %s {$activityName}活动已确定排期。";
                $msg = sprintf($msg, $info['basic_title']);
                \Biz\service\BrandIndex::writeMsg($info['brand_id'], \Biz\model\brandIndex\BrandMsg::MSG_TYPE_OVER,
                    \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
            }
            return redirect('/admin/goodsTest/index/' . $id . '/editTime?code=1');
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '活动排期失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function unPass(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info = FineGoodsModel::first(['id' => $id]);
        $info['reason'] = '';
        $form = new Form($info);
        $form->text('id', '活动ID')->readonly();
        $form->text('activity_title', '活动标题')->readonly();
        $form->text('reason', '不通过原因')->required();
        $form->action('/admin/goodsTest/index/unPassPost');
        $content->row($form);
        return $content->header('不通过原因');
    }

    public function unPassPost(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $reason = $request->input('reason', '');
            if (!$reason) {
                throw new \Exception('请填写不通过原因');
            }
            $adminId = Admin::user()->id;
            $info = FineGoodsModel::first(['id' => $id]);
            if (empty($info)) {
                throw new \Exception('不存在的活动信息');
            }
            if ($info['activity_state'] == FineGoodsModel::STATE_WAIT) {
                $data = [
                    'activity_state' => FineGoodsModel::STATE_NOT_PASS,
                    'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                    'operate_uid' => Admin::user()->id
                ];
                $result = FineGoodsModel::updateData($data, ['id' => $id]);

                //这里由于测评类型的活动 不消耗套餐权益 所以不操作
                if ($info['type'] < FineGoodsModel::TYPE_EVALUATION) {
                    $activityName = FineGoodsModel::TYPE_MAP_BACKUPS[$info['type']];
                    $msg = "你所提报的 %s {$activityName}活动未能通过审核，【%s】";
                    $reason = $request->input('reason', '');
                    if ($reason) {
                        $msg = sprintf($msg, $info['basic_title'], $reason);
                        \Biz\service\BrandIndex::writeMsg($info['brand_id'],
                            \Biz\model\brandIndex\BrandMsg::MSG_TYPE_OVER,
                            \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
                    }
                    $packageCombinationArr = json_decode($info['package_combination'], true);
                    foreach ($packageCombinationArr as $item) {
                        //GoodsTestRights::refund($info['brand_id'], $id, $item['package'], Admin::user()->id);
                        BrandEquityVerificationService::activityRightsRefund($info['brand_id'], $id,
                            BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $adminId, ['package' => $item['package']]);

                    }
                }
            } else {
                throw new \Exception('只有待审核的活动才能进行此操作');
            }
            if ($info['basic_id']) {
                BrandActivityBasic::updateActivityState($id, BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $info['basic_id'], BrandActivityBasic::ACTIVITY_STATE_DEL);
            }
            return redirect('/admin/goodsTest/index/' . $id . '/unPass?code=1');
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '审核不通过失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function audit(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $state = $request->input('state', null);
            if ($id && !is_null($state)) {
                $info = FineGoodsModel::getById(['id' => $id], false);
                switch ($state) {
                    case FineGoodsModel::STATE_PASS:
                        if ($info['activity_state'] == FineGoodsModel::STATE_WAIT) {
                            $data = [
                                'activity_state' => FineGoodsModel::STATE_PASS,
                                'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                                'operate_uid' => $adminId
                            ];
                            $result = FineGoodsModel::updateData($data, ['id' => $id]);
                            if ($result) {
                                BrandActivityBasic::updateActivityBasic($id, BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $info['brand_id'], $info['basic_id'], $info['schedule_start_time'], $info['schedule_end_time']);

                                //用户参与营销活动.好物轻测
                                \Biz\service\brand\BrandGrowth::levelTaskJoin(0, $info['brand_id']);
                            }
                            //这里由于测评类型的活动 不需要通知品牌后台 所以不操作
                            if ($info['type'] < FineGoodsModel::TYPE_EVALUATION) {
                                $activityName = FineGoodsModel::TYPE_MAP_BACKUPS[$info['type']];
                                $msg = "你所提报的 %s {$activityName}活动已通过审核。";
                                $msg = sprintf($msg, $info['basic_title']);
                                \Biz\service\BrandIndex::writeMsg($info['brand_id'],
                                    \Biz\model\brandIndex\BrandMsg::MSG_TYPE_OVER,
                                    \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_GOODS_TEST, $msg);
                            }
                        } else {
                            throw new \Exception('当前状态不能操作审核通过');
                        }
                        break;
                    case FineGoodsModel::STATE_DEL:
                        $data = [
                            'activity_state' => FineGoodsModel::STATE_DEL,
                            'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                            'operate_uid' => $adminId
                        ];
                        $result = FineGoodsModel::updateData($data, ['id' => $id]);
                        BrandActivityBasic::updateActivityState($id, BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $info['basic_id'], BrandActivityBasic::ACTIVITY_STATE_DEL);

                        //由于测评类型的活动 没有消耗套餐权益 故不操作
                        if (in_array($info['activity_state'], [FineGoodsModel::STATE_WAIT, FineGoodsModel::STATE_PASS]) && ($info['type'] < FineGoodsModel::TYPE_EVALUATION)) {
                            //活动取消，返还活动次数(待审核，审核通过)
                            //$res = GoodsTestRights::refund($info['brand_id'], $id, $info['package'], Admin::user()->id);
                            BrandEquityVerificationService::activityRightsRefund($info['brand_id'], $id, BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $adminId, ['package' => $info['package']]);
                        }
                        break;
                }
                $success = [
                    'title' => '操作成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function editDynamic(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info['request_url'] = url()->previous();
        $info['id'] = $id;
        $activityInfo = FineGoodsModel::first(['id' => $id]);
        if ($activityInfo) {
            $form = new Form($info);
            $form->hidden('id', 'id');
            $form->hidden('request_url', '');
            $form->imgUpload('dynamic_img', '中奖动态图', false, ['imgType' => ImgUrl::APPTYPE_BIZ]);
            $form->action('/admin/goodsTest/index/changeDynamic');
            $desc = '';
            $content->row($form);
        }
        return $content
            ->header('更换中奖动态图片')
            ->description($desc);
    }

    public function changeDynamic(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $dynamicImg = $request->input('dynamic_img', '');
            if (!$dynamicImg) {
                throw new \Exception('动态图片为空');
            }
            $data = [
                'dynamic_img' => $dynamicImg,
            ];
            $result = FineGoodsModel::updateData($data, ['id' => $id]);
            $redirectUrl = $request->input('request_url', '');
            $redirectUrl = $redirectUrl ? $redirectUrl : '/admin/goodsTest/index';
            return redirect($redirectUrl);;
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '更换动态图片失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public static function activityData(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        $info = FineGoodsModel::get(['id', 'activity_title', 'basic_title', 'activity_data'], ['id' => $id]);
        $form = new Form($info);
        $form->text('id', '活动id')->readonly();
        $form->text('activity_title', '活动标题')->readonly();
        $form->text('basic_title', '商品名称')->readonly();
        $form->textarea('activity_data', '活动数据')->required();
        $form->action('/admin/goodsTest/index/activityDataPost');
        return $content->header('活动数据')
            ->row($form);
    }

    public static function activityDataPost(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $activityData = $params['activity_data'] ?? '';
        try {
            if (empty($id)) {
                throw new \Exception('id为空');
            }
            $res = FineGoodsModel::updateData(['activity_data' => $activityData], ['id' => $id]);
            if ($res) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
            return redirect("/admin/goodsTest/index/'.$id.'/activityData?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    private static function getCondition($request)
    {
        $condition['ORDER'] = ['schedule_start_time' => 'DESC'];
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
            return $condition;
        }
        if (isset($request['schedule_start_time']) && strlen(trim($request['schedule_start_time'])) > 0) {
            $condition['schedule_start_time[>=]'] = strtotime($request['schedule_start_time']);
            $condition['schedule_start_time[<=]'] = strtotime($request['schedule_start_time']) + 86399;
            return $condition;
        }
        if (isset($request['goods_name']) && strlen(trim($request['goods_name'])) > 0) {
            $condition['goods_name[~]'] = trim($request['goods_name']);
        }
        if (isset($request['activity_state']) && strlen($request['activity_state']) > 0 && in_array($request['activity_state'], array_keys(FineGoodsModel::ACTIVITY_STATE))) {
            $condition = FineGoodsModel::getConditionByState($request['activity_state']);
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        } else if (isset($request['brand_name']) && strlen(trim($request['brand_name'])) > 0) {
            $condition['brand_name[~]'] = trim($request['brand_name']);
        }
        if (isset($request['type']) && !empty($request['type']) && $request['type'] < FineGoodsModel::TYPE_EVALUATION_OLD) {
            $condition['type'] = $request['type'];
        } else {
            $condition['type[<]'] = FineGoodsModel::TYPE_EVALUATION_OLD;
        }
        return $condition;
    }

    private function operateScript()
    {
        return <<<SCRIPT
        $('.grid-table').on('click', '.grid-column-copyable', (function (e) {
            var content = $(this).data('content');
            var temp = $('<input>');
            $("body").append(temp);
            temp.val(content).select();
            document.execCommand("copy");
            temp.remove();
            $(this).tooltip('show');
        }));

        $('.editTime').unbind('click').click(function() {
            var id = $(this).data('id');
            layer.open({
                type: 2,
                title: '更改排期',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/goodsTest/index/'+id+'/editTime',
            });
		});
		
        $('.pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/goodsTest/index/audit'
            let params = {id:id,state:state}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        
        $('.not-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            layer.open({
                type: 2,
                title: '不通过原因',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/goodsTest/index/'+id+'/unPass',
            });
        });
        
        
        $('.del-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/goodsTest/index/audit'
            let params = {id:id,state:state}
            layer.confirm('确定要取消活动吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            });
        });
SCRIPT;
    }

}
